<?php

$uid = 1;

// prevent this from running under apache:
//if (array_key_exists('REQUEST_METHOD', $_SERVER)) {
//    echo 'nope.  not executing except from the command line.';
//    exit(1);
//}

// set HTTP_HOST or drupal will refuse to bootstrap
 $_SERVER['HTTP_HOST'] = 'mc.uat.diagnosticimaging.dev';
 $_SERVER['REMOTE_ADDR'] = '192.168.56.1';

define('DRUPAL_ROOT', dirname(realpath(__FILE__)));

include_once 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);



//$cmp_article = new Cmpmedica_db();
//$nodes = $cmp_article->get_article_attribute();
//echo sql_to_timestamp($nodes['modifiedDate']) ;

//$liferay_canonical = set_liferay_canonical();
//echo $liferay_canonical . "\n" ;

$drupal_node = new Drupal_db();
$drupal_node->create_nodes();

//Articles to be imported
class Article {
  public $article_id;

  public function __construct() {
    $this->set_article_id();
  }

  //liferay article id to be imported
  public function set_article_id() {
    $this->article_id = 2114473;
  }

  //get liferay article id
  public function get_article_id() {
    return $this->article_id;
  }
}


//Liferay Database Class
class Cmpmedica_db {
  protected $db_host;
  protected $db_user;
  protected $db_password;
  protected $db_name;

  //Establish db connection
  public function __construct() {
    $this->db_host = "localhost";
    $this->db_user = "root";
    $this->db_password = "";
    $this->db_name = "cmpmedica";
    $liferay_conn = mysql_connect($this->db_host, $this->db_user, $this->db_password);
    $db_select = mysql_select_db($this->db_name, $liferay_conn);
  }

  public function get_article_attribute($article_id) {
    $query = "SELECT *
              FROM ArticleAttribute
              WHERE articleId = $article_id ";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    return $row;
  }

  public function get_journal_article($article_id) {
    $query = "SELECT *
              FROM JournalArticle
              WHERE articleId = $article_id ";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    return $row;
  }

  //Get home friendly url
  public function get_home_url($article_id) {
    $query = "SELECT ArticleAttribute.articleId,
              ArticleAttribute.groupId,
              Layout.friendlyURL
              FROM ArticleAttribute
              INNER JOIN Layout ON ArticleAttribute.homeURL = Layout.plid
              WHERE ArticleAttribute.articleId = $article_id ";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    return $row;

  }


}


//Drupal database class
class Drupal_db {
  protected $db_host;
  protected $db_user;
  protected $db_password;
  protected $db_name;

  //Establish db connection
  public function __construct() {
    $this->db_host = "localhost";
    $this->db_user = "root";
    $this->db_password = "";
    $this->db_name = "drupal_dev";
    $drupal_conn = mysql_connect($this->db_host, $this->db_user, $this->db_password);
    $db_select = mysql_select_db($this->db_name, $drupal_conn);
  }


  // create the node object
  function create_nodes() {

    $article = new Article();
    $article_id = $article->get_article_id();

    //Get data from liferay database
    $cmp_article = new Cmpmedica_db();
    $article_attribute = $cmp_article->get_article_attribute($article_id);
    $journal_article = $cmp_article->get_journal_article($article_id);

    $node = new stdClass();
    $node->type = 'article';
    $node->status = 1;
    $node->uid = 1;
    $node->title = $article_attribute['headline'];
    $node->body['und'][0]['format'] = 'full_html';
    $node->body['und'][0]['value'] = XML2HTML($journal_article['content']);
    $node->created = sql_to_timestamp($article_attribute['createDate']);
    $node->changed = sql_to_timestamp($article_attribute['modifiedDate']);
    $node->promote = 1;
    $node->sticky = 0;
    $node->format = 1;
    $node->language = 'und';

    //Fields
    if (!empty($article_attribute['byline']) || $article_attribute['byline'] != null) {
      $node->field_author['und'][0]['tid'] =  get_tid_from_author_name($article_attribute['byline']);
      $node->field_byline['und'][0]['value'] = $article_attribute['byline'];
    }
    $node->field_display_date['und'][0]['value'] = $journal_article['displayDate'];
    $node->field_liferay_canonical['und'][0]['value'] = set_liferay_canonical();

    $node = node_submit($node);
    node_save($node);
  }

}

/*--------------------------------Helper functions--------------------------------*/

//Convert SQL time to timestamp
function sql_to_timestamp($sql_time) {
  $timestamp = strtotime($sql_time);
  return $timestamp;
}

//Parse xml into html for article body
function XML2HTML($content) {
  libxml_use_internal_errors(TRUE);
  if ($xml = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA)) {
    $xml = (array) $xml;
    $body = (string) $xml['static-content'];
    $body = cleanEncoding($body);
    return $body;
  }
}

//Clean utf8 encoding
function cleanEncoding($text) {
  $text = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text);
  return $text;
}

//Get taxonomy id from for author name
function get_tid_from_author_name($byline) {
  $tid = '';
  if (!empty($byline) || $byline != NULL) {
    $terms = parsebyline($byline);
    foreach ($terms as $term) {
      $term = taxonomy_get_term_by_name($term);
      foreach ($term as $term_value) {
        $tid = $term_value->tid;
      }
    }
    return $tid;
  }
}

//Returns an array of parsed author tags/taxonomy terms
function parseByline($byline) {
  $byline = str_replace('<BR>', '<br>',trim($byline));
  $search= array('PharmD','FRCPsych','MB','M.D.','M.P.H.','Ph.D.','F.A.C.S','D.N.S.','R.N.','MA','Mba','DO', 'MD','PhD','PA-C','FACP','DrPH', 'CS',"RN",'MSN','FACS','Jr','NP','MPH','Sr','ScD','MS','MBBS', 'MRCP','BSc','MBBS','FRCP','FRCPEd','MRCP',"JD");
  $byline = str_replace(',and ',' and ', $byline);
  foreach($search as $mas) {
    $byline = str_replace(', '.$mas,'#'.$mas,$byline);
  }
  $byline = explode('<br>', $byline);
  $p = array();
  foreach($byline as $line) {
    $parts = explode(',', $line);
    foreach($parts as $part) {
      $part = str_replace(', and',',', $part);
      $part = str_replace(' and ',',', $part);
      $part = str_replace(', ,',',', $part);
      $part = str_replace(',,',',', $part);
      $p2 = explode(',',$part);
      foreach($p2 as $author) {
        $author = trim(strip_tags($author));
        if(substr($author,0, 3) == 'By ') {
          $author = substr($author, 3);
        }
        $author = str_replace(' By ','', $author);
        if($author) {
          $p[] = $author;
        }
      }
    }
  }
  foreach($p as $tag) {
    if(strstr($tag,'#')) {
      $name = explode('#', $tag);
      $name[0] = ucwords(strtolower($name[0]));
      $tag = implode($name, '#');
      $tag = str_replace('#', ', ',$tag);
      $tag = $tag;

      $tags[] = strip_tags($tag);
    }
    else if(count($p) < 2) {
      $tags[] = ucwords(strtolower($tag));
    }
  }
  if(isset($tags)) {
    return $tags;
  }
}

/*
 * Liferay canonical
 * Get url from group id
 */
function grouptourl($group) {
  $group_map = array(
    1145622 => 'http://www.musculoskeletalnetwork.com',
    10168 => 'http://www.psychiatrictimes.com',
    10162 => 'http://www.consultantlive.com',
    10165 => 'http://www.cancernetwork.com',
    113619 => 'http://www.diagnosticimaging.com',
    1760982 => 'http://hcp.obgyn.net',
    1803329 => 'http://www.pediatricsconsultantlive.com',
    1462168   => 'http://www.physicianspractice.com'
  );
  if($group_map[$group]) {
    return $group_map[$group];
  }
  return $group;
}

//Set liferay canonical url
function set_liferay_canonical() {

  $article = new Article();
  $article_id = $article->get_article_id();

  $cmp_article = new Cmpmedica_db();
  $article_attribute = $cmp_article->get_article_attribute($article_id);

  $groupurl = grouptourl($article_attribute['groupId']);

  $home_url = $cmp_article->get_home_url($article_id);
  $friendly_url = $home_url['friendlyURL'];

  $group_id = $article_attribute['groupId'];

  $liferay_canonical = $groupurl . $friendly_url . '/' . $group_id . '/' . $article_id;

  return $liferay_canonical;
}